import axios from "uniapp-axios-adapter";
import appConfig from "@/config/index.js";
console.log(appConfig.baseApi)


axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
const service = axios.create({
	// #ifdef H5
	baseURL: import.meta.env.VITE_APP_API_BASEURL,
	// headers: {
	// 	'content-type': 'application/x-www-form-urlencoded;charset=utf-8'
	// },
	  timeout: 10000,
	
	// #endif
	
  baseURL: appConfig.baseApi,
  timeout: 10000,
});
service.interceptors.request.use((config) => {
  console.log('请求拦截器: ', config);

  //带上token
  // config.headers["Authorization"] = "token";
  return config;
});

service.interceptors.response.use((response) => {
  console.log('响应拦截器: ', response);
  // 统一处理响应,返回Promise以便链式调用



  if (response.status === 200) {
    const {
      data
    } = response;
    if (data && data.code === 200) {
      return Promise.resolve(data);
    } else {
      return Promise.reject(data);
    }
  } else {
    return Promise.reject(response);
  }
});


function request(options) {
  //纠正get
  options.method = options.method?.toLowerCase() || "get";
  if (options.method == "get") {
    options.params = options.data;
  }
  //？？空值合并运算符 二取 1非空
  const isMock = options.mock ?? appConfig.mock;

  //生产，我希望可以用mock当第二个api接口
  service.defaults.baseURL = isMock ? appConfig.mockApi : appConfig.baseApi;
  return service(options);

}

["get", "post", "put", "delete", "patch"].forEach((method) => {
  request[method] = (url, data, options) => {
    return request({
      url,
      data,
      method,
      ...options
    })
  }


})


export default request;